package logic

import (
	"context"
	"fmt"
	"github.com/pkg/errors"
	"my-zero-tiktok/apps/comment/models"
	"my-zero-tiktok/common/constant"
	"my-zero-tiktok/common/xerr"

	"my-zero-tiktok/apps/comment/pb/pb"
	"my-zero-tiktok/apps/comment/rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type DelCommentLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDelCommentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelCommentLogic {
	return &DelCommentLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// DelComment 删除评论
func (l *DelCommentLogic) DelComment(in *pb.IDRequest) (*pb.Empty, error) {
	comment, err := l.svcCtx.CommentModel.FindOne(l.ctx, in.Id)
	if err != nil {
		if errors.Is(err, models.ErrNotFound) {
			return nil, xerr.New(xerr.CommentNotExistError)
		}

		return nil, xerr.New(xerr.CommentGetError)
	}

	err = l.svcCtx.CommentModel.Delete(l.ctx, in.Id)
	if err != nil {
		return nil, xerr.New(xerr.CommentDelError)
	}

	comVideoKey := fmt.Sprintf("%s:%d", constant.ComVideoKey, comment.VideoId)
	_, _ = l.svcCtx.Redis.ZremCtx(l.ctx, comVideoKey, fmt.Sprintf("%d", in.Id))
	return &pb.Empty{}, nil
}
